package com.paddyi.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.paddyi.model.SsoUser;
import com.paddyi.service.ISsoUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;

/**
 * 自定义的UserDetailsService,实现loadUserByUsername方法
 * 查询用户,如果查询到返回用户和用户所拥有的角色
 */
@Service
public class MyUserDetailsService implements UserDetailsService {


    @Autowired
    private ISsoUserService userService;

    /**
     *
     */

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<SsoUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name",username);
        SsoUser user = userService.getOne(queryWrapper);
        if (user == null) {
            throw new UsernameNotFoundException(username);
        }
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority("user"));

        return new User(user.getName(), user.getPassword(), authorities);
    }
}
